package com.zeng.controller;

import com.zeng.common.Constants;
import com.zeng.dao.ComplaintDao;
import com.zeng.dao.ComplaintsDao;
import com.zeng.entity.Userinfo;
import com.zeng.service.AuditService;
import com.zeng.service.LogsinfoService;
import com.zeng.service.UserinfoService;
import com.zeng.service.VicodeinfoService;
import com.zeng.utils.getUserIp;
import com.zeng.entity.*;
import com.zeng.utils.TimeUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * (Userinfo)表控制层
 *
 * @author zengfanchao
 * @since 2021-03-17 19:17:00
 */
@RestController
@RequestMapping("userinfo")
public class UserinfoController {
    /**
     * 服务对象
     */
    @Resource
    private UserinfoService userinfoService;
    @Resource
    private VicodeinfoService vicodeinfoService;
    @Resource
    private LogsinfoService logsinfoService;
    @Resource
    private AuditService auditService;
    @Resource
    private ComplaintsDao complaintsDao;
    @Resource
    private ComplaintDao complaintDao;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Userinfo selectOne(Integer id) {
        return this.userinfoService.queryById(id);
    }

    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping("selectAll")
    public List<Userinfo> selectAll() {
        return this.userinfoService.selectAll();
    }

    /**
     * 根据页号查询
     *
     * @param offset 查询初始位置
     * @param limit  查询数量
     * @return
     */
    @GetMapping("selectAllByLimit")
    public ResultPage selectAllByLimit(int offset, int limit) {
        int pageTotal = this.userinfoService.queryCount();
        List<Userinfo> list = this.userinfoService.queryAllByLimit(offset, limit);
        return ResultPage.success(pageTotal, "请求成功", list);
    }

    @PostMapping("selectKeyByLimit")
    public ResultPage selectKeyByLimit(@RequestBody HashMap<String, String> map) {
        ResultPage resultPage = new ResultPage();
        if (map.get("key").equals("")) {
            int pageTotal = this.userinfoService.queryCount();
            List<Userinfo> list = this.userinfoService.queryAllByLimit(Integer.valueOf(map.get("offset")), Integer.valueOf(map.get("limit")));
            resultPage.setData(list);
            resultPage.setPageTotal(pageTotal);
        } else {
            int pageTotal = this.userinfoService.queryCountSelect(map.get("key"));
            List<Userinfo> list = this.userinfoService.queryKeyByLimit(map.get("key"), Integer.valueOf(map.get("offset")), Integer.valueOf(map.get("limit")));
            resultPage.setData(list);
            resultPage.setPageTotal(pageTotal);
        }
        return resultPage;
    }

//    @GetMapping("selectKey")
//    public List<Userinfo> selectKey(String key) {
//        List<Userinfo> list = this.userinfoService.selectKey(key);
//        return list;
//    }
//
//    @GetMapping("selectByEntity")
//    public List<Userinfo> selectByEntity(@RequestBody HashMap<String, String> map) {
//        Userinfo userinfo = new Userinfo();
//        List<Userinfo> list = this.userinfoService.selectByEntity(userinfo);
//        return list;
//    }

    @GetMapping("deleteById")
    public String deleteById(Integer id) {
        this.userinfoService.deleteById(id);
        return null;
    }

    @RequestMapping("edit")
    public Result edit(@RequestBody HashMap<String, String> map
    ) {
        Userinfo userinfo = this.userinfoService.queryById(Integer.valueOf(map.get("uid")));
        userinfo.setUserstate(Integer.valueOf(map.get("userstate")));
        userinfo.setIscert(Integer.valueOf(map.get("iscert")));
        userinfo.setIsseller(Integer.valueOf(map.get("isseller")));
        userinfo.setUsername(map.get("username"));
        userinfo.setPwd(map.get("pwd"));
        userinfo.setMail(map.get("mail"));
        userinfo.setTel(map.get("tel"));
        userinfo.setStudentid(map.get("studentid"));
        userinfo.setName(map.get("name"));
        userinfo.setPhotourl(map.get("photourl"));
        userinfo.setStucardurl(map.get("stucardurl"));
        userinfoService.update(userinfo);
        return Result.success("修改成功");
    }

    @RequestMapping("editstu")
    public Result editstu(@RequestBody HashMap<String, String> map, HttpServletRequest request
    ) {
        Userinfo userinfo = this.userinfoService.queryById(Integer.valueOf(map.get("uid")));
        userinfo.setIscert(1);
        userinfo.setStucardurl(map.get("stucardurl"));
        userinfoService.update(userinfo);
        //修改审核表
        Audit audit = new Audit();
        audit.setAuditstate("2");
        audit.setDetails("学生身份审核");
        audit.setCreatetime(TimeUtils.NowTimeN());
        audit.setUid(Integer.valueOf(map.get("uid")));
        audit.setAuditimg(map.get("stucardurl"));
        audit.setKinds("1");
        this.auditService.insert(audit);
        //写日志
        //(String operator, Date createtime, String createip, String details, String note)
        logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), new getUserIp().getIp(request), audit.getDetails(), "提交学生审核"));


        return Result.success("提交学生审核成功");
    }

    @RequestMapping("editSeller")
    public Result editSeller(@RequestBody HashMap<String, String> map, HttpServletRequest request
    ) {
        Userinfo userinfo = this.userinfoService.queryById(Integer.valueOf(map.get("uid")));
        userinfo.setIsseller(1);
        userinfoService.update(userinfo);
        //修改审核表
        Audit audit = new Audit();
        audit.setAuditstate("2");
        audit.setDetails("商家身份审核");
        audit.setCreatetime(TimeUtils.NowTimeN());
        audit.setUid(Integer.valueOf(map.get("uid")));
        audit.setKinds("0");
        this.auditService.insert(audit);
        //写日志
        //(String operator, Date createtime, String createip, String details, String note)
        logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), new getUserIp().getIp(request), audit.getDetails(), "提交学生审核"));
        return Result.success("提交商家审核成功");
    }

    @RequestMapping("editpwd")
    public Result editpwd(@RequestBody HashMap<String, String> map, HttpServletRequest request
    ) {
        String oldp = map.get("oldpwd");
        String newp = map.get("newpwd");
        String renewp = map.get("renewpwd");

        Userinfo userinfo = this.userinfoService.queryById(Integer.valueOf(map.get("uid")));
        if (oldp.equals(userinfo.getPwd())) {
            if (newp.equals(renewp)) {
                userinfo.setPwd(newp);
                this.userinfoService.update(userinfo);
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户修改密码", "修改成功"));
                return Result.success("修改成功");
            } else {
                logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户修改密码", "确认密码失败"));
                return Result.error("确认密码失败");
            }
        } else {
            logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户修改密码", "旧密码输入错误"));
            return Result.error("旧密码输入错误");
        }
    }

    /**
     * 用户找回密码
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("repwd")
    public Result repwd(@RequestBody HashMap<String, String> map, HttpServletRequest request
    ) {
        Vicodeinfo vicodeinfo = vicodeinfoService.checkViCode(map.get("mail"));
        if (!vicodeinfo.getVicode().equals(map.get("iscode")))
            return Result.error("验证码错误");
        if (TimeUtils.minsBetween(vicodeinfo.getCreatetime(), TimeUtils.NowTimeN()) <= 5) {
            if (vicodeinfo.getVicode().equals(map.get("iscode"))) {
                Userinfo userinfo = userinfoService.queryByEmail(map.get("mail"));
                userinfo.setPwd(map.get("password"));
                this.userinfoService.update(userinfo);
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "密码找回", "找回成功"));
                return Result.success("找回成功");
            } else {
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "密码找回", "验证码错误"));
                return Result.error("验证码错误");
            }
        } else {
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "密码找回", "验证码失效"));
            return Result.error("验证码失效");
        }
    }

    @RequestMapping("add")
    public Result add(@RequestBody HashMap<String, String> map, HttpServletRequest request
    ) {
        Vicodeinfo vicodeinfo = vicodeinfoService.checkViCode(map.get("mail"));
        if (!vicodeinfo.getVicode().equals(map.get("iscode")))
            return Result.error("验证码错误");
        if (TimeUtils.minsBetween(vicodeinfo.getCreatetime(), TimeUtils.NowTimeN()) <= 5) {
            if (vicodeinfo.getVicode().equals(map.get("iscode"))) {
                Userinfo userinfo = new Userinfo();
                userinfo.setMail(map.get("mail"));
                userinfo.setPwd(map.get("password"));
                userinfo.setTel(map.get("tel"));
                userinfo.setUsername(map.get("username"));
                userinfo.setStucardurl("http://127.0.0.1:8000/images/detault/upStu.png");
                userinfo.setPhotourl("http://127.0.0.1:8000/images/head/dft.jpg");
                userinfo.setCreatetime(TimeUtils.NowTimeN());
                userinfo.setDeleteflag(0);
                userinfo.setIscert(0);
                userinfo.setIsseller(0);
                userinfo.setUserstate(0);
                userinfoService.insert(userinfo);
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户注册", "注册成功"));
                return Result.success("注册成功");
            } else {
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户注册", "验证码错误"));
                return Result.error("验证码错误");
            }
        } else {
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户注册", "验证码失效"));
            return Result.error("验证码失效");
        }
    }


    /**
     * 用户申诉
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("shensu")
    public Result shensu(@RequestBody HashMap<String, String> map, HttpServletRequest request
    ) {
        Userinfo userinfo = userinfoService.queryByEmail(map.get("mail"));
        if (userinfo != null) {
            if (userinfo.getUserstate() == 0) {
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户申诉", "此用户无需申诉"));
                return Result.error("此用户无需申诉");
            }
            if (userinfo.getUserstate() == 1 || userinfo.getUserstate() == 3) {
                Complaint complaint = new Complaint();
                complaint.setCreatetime(TimeUtils.NowTimeN());
                complaint.setDetails(map.get("details"));
                complaint.setState("未处理");
                complaint.setUid(userinfo.getUid());
                this.complaintDao.insert(complaint);

                userinfo.setUserstate(2);
                this.userinfoService.update(userinfo);
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户申诉", "申诉成功"));
                return Result.success("申诉成功，请等待管理员审核");
            } else
                //写日志
                //(String operator, Date createtime, String createip, String details, String note)
                logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户申诉", "有申诉未处理"));
            return Result.error("有申诉未处理，等待管理员审核");
        } else {
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(map.get("mail"), TimeUtils.NowTimeN(), new getUserIp().getIp(request), "用户申诉", "申诉失败"));
            return Result.error("申诉失败，请重新提交申诉");
        }
    }

    /**
     * 用户投诉
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("tousu")
    public Result tousu(@RequestBody HashMap<String, String> map, HttpServletRequest request
    ) {
        if (map.get("uid").equals(map.get("eduid"))) {
            return Result.error("不能投诉自己");
        }
        if (map.get("eduid").equals("1001")) {
            return Result.error("商家自营账号，请联系QQ132654321");
        }
        Complaints complaints = new Complaints();
        complaints.setCreatetime(TimeUtils.NowTimeN());
        complaints.setDetails(map.get("details"));
        complaints.setState("未处理");
        complaints.setUid(Integer.valueOf(map.get("uid")));
        complaints.setEduid(Integer.valueOf(map.get("eduid")));
        this.complaintsDao.insert(complaints);
        return Result.success("投诉成功");
    }

    @PostMapping("login")
    public Result login(@RequestBody HashMap<String, String> map, HttpServletResponse response, HttpServletRequest request) {

        Userinfo userinfo = userinfoService.queryByEmail(map.get("mail"));
        //定位IP
        String userip = new getUserIp().getIp(request);
        if (userinfo == null) {
            //写日志
            logsinfoService.insert(new Logsinfo("visitor", TimeUtils.NowTimeN(), userip, "用户登录", "用户不存在"));
            return Result.error("账号不存在或密码错误");
        }
        if (!userinfo.getPwd().equals(map.get("pwd"))) {
            //写日志
            logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), userip, "用户登录", "密码错误"));
            return Result.error("账号不存在或密码错误");
        }
        if (userinfo.getUserstate() == Constants.USER_WRONG) {
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), userip, "用户登录", "用户已被封禁"));
            return Result.error("用户被封禁");
        }
        if (userinfo.getUserstate() == Constants.USER_WAIT) {
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), userip, "用户登录", "用户申诉未审核"));
            return Result.error("请等待管理员审核");
        }
        if (userinfo.getUserstate() == Constants.USER_WAIT_REMOVE) {
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), userip, "用户登录", "申诉被驳回，用户被封禁"));
            return Result.error("申诉被驳回，用户被封禁");
        }
        //更新用户登陆IP状态
        userinfo.setLoginip(userip);
        userinfo.setLogintime(TimeUtils.NowTimeN());
        userinfoService.update(userinfo);
        //写日志
        //(String operator, Date createtime, String createip, String details, String note)
        logsinfoService.insert(new Logsinfo(userinfo.getMail(), TimeUtils.NowTimeN(), userip, "用户登录", "登陆成功"));
        return Result.success("登录成功", userinfo);
    }
}